package org.tinaelle.hibernate;

import java.io.Serializable;
import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.persister.entity.AbstractEntityPersister;
import org.hibernate.type.Type;
import org.tinaelle.ServiceLocator;
import org.tinaelle.server.domain.AdObject;
import org.tinaelle.server.service.AdSequenceService;

public class AdSequenceGenerator implements IdentifierGenerator, Configurable {

	public Serializable generate(final SessionImplementor session, final Object object) throws HibernateException {
		final AbstractEntityPersister classMetaData = ( AbstractEntityPersister ) session.getFactory()
		        .getClassMetadata( object.getClass() );
		final AdSequenceService adSequenceService = ServiceLocator.instance().getAdSequenceService();
		if ( object instanceof AdObject ) {
			AdObject adObject = ( AdObject ) object;
			if ( adObject.getClient().getAdClientId().intValue() == 0 ) {
				return new Integer( adSequenceService.getNextSystemId( classMetaData.getTableName() ) );
			} else {
				return new Integer( adSequenceService.getNextId( classMetaData.getTableName() ) );
			}
		} else {
			throw new HibernateException( "This entity is not managed." );
		}
	}

	public void configure(final Type type, final Properties params, final Dialect d) throws MappingException {
		// TODO Auto-generated method stub

	}
}
